<?php

/* $Revision: 1.35 $ */

$PageSecurity=1;

include('includes/session.inc');

$ModuleList = array(_('Orders'), 
					_('Receivables'), 
					_('Payables'), 
					_('Purchasing'), 
					_('Inventory'), 
					_('Manufacturing'), 
					_('General Ledger'), 
					_('Setup'));

$title = _('Quản lí người dùng');
include('includes/header.inc');

echo '<p class="page_title_text"><img src="'.$rootpath.'/css/'.$theme.'/images/group_add.png" title="' . _('Search') . '" alt="">' . ' ' . $title.'<br>';

// Make an array of the security roles

$SecurityRoles = _single('api/securityroles')->GetSecurityRolesList($_SESSION['UserID'], $_SESSION['Password']);

if (isset($_GET['SelectedUser'])){
	$SelectedUser = $_GET['SelectedUser'];
} elseif (isset($_POST['SelectedUser'])){
	$SelectedUser = $_POST['SelectedUser'];
}

if (isset($_POST['submit'])) {

	//initialise no input errors assumed initially before we test
	$InputError = 0;

	/* actions to take once the user has clicked the submit button
	ie the page has called itself with some user input */
	//first off validate inputs sensible
	if (strlen($_POST['UserID'])<3){
		$InputError = 1;
		prnMsg(_('The user ID entered must be at least 4 characters long'),'error');
	} elseif (ContainsIllegalCharacters($_POST['UserID'])) {
		$InputError = 1;
		prnMsg(_('User names cannot contain any of the following characters') . " - ' & + \" \\ " . _('or a space'),'error');
	} elseif (strlen($_POST['Password'])<5){
		if (!$SelectedUser){
			$InputError = 1;
			prnMsg(_('The password entered must be at least 5 characters long'),'error');
		}
	} elseif (strstr($_POST['Password'],$_POST['UserID'])!= False){
		$InputError = 1;
		prnMsg(_('The password cannot contain the user id'),'error');
	} elseif (strlen($_POST['Phone']) > 50) {
        $InputError = 1;
		prnMsg(_('Số điện thoại phải nhỏ hơn hay bằng 50 ký tự'),'error');
    } elseif (strlen($_POST['Email']) > 0 and strlen($_POST['Email']) > 55) {
        $InputError = 1;
		prnMsg(_('Địa chỉ mail phải nhỏ hơn hay bằng 55 ký tự'),'error');
    } elseif (strlen($_POST['Email']) > 0 and !IsEmailAddress($_POST['Email'])) {
        $InputError = 1;
		prnMsg(_('Địa chỉ mail không đúng dạng chuẩn'),'error');
    }

	/* Make a comma separated list of modules allowed ready to update the database*/
	$i=0;
	$ModulesAllowed = '';
	while ($i < count($ModuleList)){
		$FormVbl = "Module_" . $i;
		$ModulesAllowed .= 1 . ',';
		$i++;
	}
	$_POST['ModulesAllowed']= $ModulesAllowed;


	if ($SelectedUser AND $InputError !=1) {

/*SelectedUser could also exist if submit had not been clicked this code would not run in this case cos submit is false of course  see the delete code below*/

		if (!isset($_POST['SalesMan']) OR $_POST['SalesMan']==NULL OR $_POST['SalesMan']==''){
			$_POST['SalesMan']='';
		}
		if (!isset($_POST['BranchCode']) OR $_POST['BranchCode']==NULL OR $_POST['BranchCode']==''){
			$_POST['BranchCode']='';
		}
		$UpdatePassword = "";
		if ($_POST['Password'] != ""){
			$UpdatePassword = "password='" . CryptPass($_POST['Password']) . "',";
		}
		
		//print_r($_POST);exit;
		$UserDetails = array(
			'realname' => $_POST['RealName'],
			'password' => CryptPass($_POST['Password']),
			'phone' => $_POST['Phone'],
			'email' => $_POST['Email'],
			'salesman' => $_POST['SalesMan'],
			'branchcode' => $_POST['BranchCode'],
			'modulesallowed' => $ModulesAllowed,
			'fullaccess' => $_POST['Access'],
			'theme' => $_POST['Theme'],
			'blocked' => $_POST['Blocked']
		);
		
		$Msg = _('Thông tin người dùng đã được cập nhật.');
		$Errors = _single('api/user')->ModifyUser($SelectedUser, $UserDetails, $_SESSION['UserID'], $_SESSION['Password']);
		$ErrMsg = _('Thông tin người dùng chưa cập nhật vì');		
	} elseif ($InputError !=1) {

		$UserDetails = array(
			'userid' => $_POST['UserID'],
			'realname' => $_POST['RealName'],
			'password' => $_POST['Password'],
			'phone' => $_POST['Phone'],
			'email' => $_POST['Email'],
			'salesman' => $_POST['SalesMan'],
			'branchcode' => $_POST['BranchCode'],
			'modulesallowed' => $ModulesAllowed,
			'fullaccess' => $_POST['Access'],
			'theme' => $_POST['Theme'],
			'blocked' => $_POST['Blocked']
		);
		$Errors = _single('api/user')->InsertUser(DB_escape_string($_POST['UserID']), $UserDetails, $_SESSION['UserID'], $_SESSION['Password']);
		$Msg = _('Người dùng mới đã tạo.');
		$ErrMsg = _('Thông tin người dùng chưa được tạo vì');
	}
	
	if($Errors[0] == 0){
      	prnMsg(_($Msg), 'success');        
	}else{
		prnMsg($ErrMsg.', '.print_r($Errors), 'error');
	}
	if ($InputError!=1){
		//run the SQL from either of the above possibilites
		/*$ErrMsg = _('The user alterations could not be processed because');
		$DbgMsg = _('The SQL that was used to update the user and failed was');
		$result = DB_query($sql,$db,$ErrMsg,$DbgMsg);*/

		unset($_POST['UserID']);
		unset($_POST['RealName']);
		unset($_POST['BranchCode']);
		unset($_POST['Salesman']);
		unset($_POST['Phone']);
		unset($_POST['Email']);
		unset($_POST['Password']);
		unset($_POST['Access']);
		unset($_POST['Blocked']);
		unset($_POST['Theme']);
		unset($SelectedUser);
	}

} elseif (isset($_GET['delete'])) {
//the link to delete a selected record was clicked instead of the submit button

	// comment out except for demo!  Do not want anyopne deleting demo user.
	/*
	if ($SelectedUser == 'demo') {
		prnMsg(_('The demonstration user called demo cannot be deleted'),'error');
	} else {
	*/
		$sql='SELECT userid FROM audittrail where userid="'. $SelectedUser .'"';
		$result=DB_query($sql, $db);
		if (DB_num_rows($result)!=0) {
			prnMsg(_('Cannot delete user as entries already exist in the audit trail'), 'warn');
		} else {

			$sql="DELETE FROM www_users WHERE userid='$SelectedUser'";
			$ErrMsg = _('The User could not be deleted because');;
			$result = DB_query($sql,$db,$ErrMsg);
			prnMsg(_('User Deleted'),'info');
		}
		unset($SelectedUser);
	// }

}

if (!isset($SelectedUser)) {

/* If its the first time the page has been displayed with no parameters then none of the above are true and the list of Users will be displayed with links to delete or edit each. These will call the same page again and allow update/input or deletion of the records*/

	$result = _single('api/user')->GetUserList($_SESSION['UserID'], $_SESSION['Password']);

	echo '<center><br/>';
	echo '<table border=1 class="pretty-table">';
	echo "<tr><th>" . _('Tên đăng nhập') . "</th>
		<th>" . _('Họ và tên') . "</th>
		<th>" . _('Điện thoại') . "</th>
		<th>" . _('Email') . "</th>
		<th>" . _('Chức vụ') . "</th>
		<th>" . _('Địa chỉ thường trú') . "</th>
		<th>" . _('Lần cuối cùng đăng nhập') . "</th>
		<th>" . _('Quyền hạn truy cập') ."</th>
		<th>" . _('Giao diện quản lí') ."</th>
		<th>" . _(' ') ."</th>
		<th>" . _(' ') ."</th>	
	</tr>";

	$k=0; //row colour counter

	while ($myrow = DB_fetch_array($result, SQLSRV_FETCH_ASSOC)) {
		if ($k==1){
			echo '<tr class="EvenTableRows">';
			$k=0;
		} else {
			echo '<tr class="OddTableRows">';
			$k=1;
		}

		//$LastVisitDate = ConvertSQLDate($myrow[6]);

		/*The SecurityHeadings array is defined in config.php */
		$UserId = $myrow['userid'];
		$RealName = $myrow['realname'];
		$Phone = $myrow['phone'];
		$Email = $myrow['email'];
		$SalesMan = $myrow['salesman'];
		$BranchCode = $myrow['branchcode'];
		$LastDate = $myrow['lastvisitdate'];
		$FullAccess = $myrow['fullaccess'];
		$Theme = $myrow['theme'];

		printf("<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td>%s</td>
					<td><a href=\"%s&SelectedUser=%s\">" . _('Cập nhật') . "</a></td>
					<td><a href=\"%s&SelectedUser=%s&delete=1\">" . _('Xóa') . "</a></td>
					</tr>",
					$UserId,
					$RealName,
					$Phone,
					$Email,
					$SalesMan,
					$BranchCode,					
					$LastDate,
					$SecurityRoles[$FullAccess],
					$Theme,
					$_SERVER['PHP_SELF']  . "?" . SID,
					$UserId,
					$_SERVER['PHP_SELF'] . "?" . SID,
					$UserId);

	} //END WHILE LIST LOOP
	echo '</table><br>';
	echo '</center>';
} //end of ifs and buts!


if (isset($SelectedUser)) {
	echo "<div class='centre'><a href='" . $_SERVER['PHP_SELF'] ."?" . SID . "'>" . _('Quay về danh sách người dùng') . '</a></div><br>';
}

echo '<center>';
echo "<form method='post' action=" . $_SERVER['PHP_SELF'] . "?" . SID . ">";

if (isset($SelectedUser)) {
	//editing an existing User

	$myrow = _single('api/user')->GetUserById($SelectedUser, $_SESSION['UserID'], $_SESSION['Password']);

	$_POST['UserID'] = $myrow['userid'];
	$_POST['RealName'] = $myrow['realname'];
	$_POST['Phone'] = $myrow['phone'];
	$_POST['Email'] = $myrow['email'];
	$_POST['BranchCode']  = $myrow['branchcode'];
	$_POST['Salesman'] = $myrow['salesman'];
	$_POST['Access'] = $myrow['fullaccess'];
	$_POST['Theme'] = $myrow['theme'];
	$_POST['Blocked'] = $myrow['blocked'];
	
	echo "<input type='hidden' name='SelectedUser' value='" . $SelectedUser . "'>";
	echo "<input type='hidden' name='UserID' value='" . $_POST['UserID'] . "'>";

	echo '<table> <tr><td>' . _('Tên đăng nhập') . ':</td><td>';
	echo $_POST['UserID'] . '</td></tr>';

} else { //end of if $SelectedUser only do the else when a new record is being entered

	echo '<table><tr><td>' . _('Tên đăng nhập') . ":</td><td><input type='text' name='UserID' size=22 maxlength=20 ></td></tr>";

	/*set the default modules to show to all
	this had trapped a few people previously*/
	$i=0;
	if (!isset($_POST['ModulesAllowed'])) {
		$_POST['ModulesAllowed']='';
	}
	foreach($ModuleList as $ModuleName){
		if ($i>0){
			$_POST['ModulesAllowed'] .=',';
		}
		$_POST['ModulesAllowed'] .= '1';
		$i++;
	}
}

if (!isset($_POST['Password'])) {
	$_POST['Password']='';
}
if (!isset($_POST['RealName'])) {
	$_POST['RealName']='';
}
if (!isset($_POST['Phone'])) {
	$_POST['Phone']='';
}
if (!isset($_POST['Email'])) {
	$_POST['Email']='';
}
echo '<tr><td>' . _('Mật khẩu') . ":</td>
	<td><input type='password' name='Password' size=22 maxlength=20 value='" . $_POST['Password'] . "'></tr>";
echo '<tr><td>' . _('Họ và tên') . ":</td>
	<td><input type='text' name='RealName' value='" . $_POST['RealName'] . "' size=36></td></tr>";
echo '<tr><td>' . _('Điện thoại') . ":</td>
	<td><input type='text' name='Phone' value='" . $_POST['Phone'] . "' size=32></td></tr>";
echo '<tr><td>' . _('Địa chỉ mail') .":</td>
	<td><input type='text' name='Email' value='" . $_POST['Email'] ."' size=32></td></tr>";

if (!isset($_POST['SalesMan'])) {
	$_POST['SalesMan']='';
}
if (!isset($_POST['BranchCode'])) {
	$_POST['BranchCode']='';
}

echo '<tr><td>' . _('Chức vụ') . ':</td>
	<td><input type="text" name="SalesMan" size=40 value="' . $_POST['SalesMan'] . '"></td></tr>';

echo '<tr><td>' . _('Địa chỉ thường trú') . ':</td>
	<td><input type="text" name="BranchCode" size=60 VALUE="' . $_POST['BranchCode'] .'"></td></tr>';

echo '<tr><td>' . _('Quyền hạn truy cập') . ":</td><td><select name='Access'>";
foreach ($SecurityRoles as $SecKey => $SecVal) {
	if (isset($_POST['Access']) and $SecKey == $_POST['Access']){
		echo "<option selected value=" . $SecKey . ">" . $SecVal;
	} else {
		echo "<option value=" . $SecKey . ">" . $SecVal;
	}
}
echo '</select></td></tr>';
echo '<input type="hidden" name="ID" value="'.$_SESSION['UserID'].'">';

echo '<tr>
	<td>' . _('Giao diện quản lí') . ":</td>
	<td><select name='Theme'>";

$ThemeDirectory = dir('css/');


while (false != ($ThemeName = $ThemeDirectory->read())){

	if (is_dir("css/$ThemeName") AND $ThemeName != '.' AND $ThemeName != '..' AND $ThemeName != '.svn'){

		if (isset($_POST['Theme']) and $_POST['Theme'] == $ThemeName){
			echo "<option selected value='$ThemeName'>$ThemeName";
		} else if (!isset($_POST['Theme']) and ($_SESSION['DefaultTheme']==$ThemeName)) {
			echo "<option selected value='$ThemeName'>$ThemeName";
		} else {
			echo "<option value='$ThemeName'>$ThemeName";
		}
	}
}

echo '</select></td></tr>';

echo '<tr><td>' . _('Trạng thái tài khoản') . ":</td><td><select name='Blocked'>";
if ($_POST['Blocked']==0){
	echo '<option selected value=0>' . _('Mở');
	echo '<option value=1>' . _('Khóa');
} else {
 	echo '<option selected value=1>' . _('Khóa');
	echo '<option value=0>' . _('Mở');
}
echo '</select></td></tr>';

echo '</table><br>
	<div class="centre"><input type="submit" name="submit" value="' . _('Cập nhật thông tin') . '"></div>
	</form>';
echo '</center>';

if (isset($_GET['SelectedUser'])) {
	echo '<script  type="text/javascript">defaultControl(document.forms[0].Password);</script>';
} else {
	echo '<script  type="text/javascript">defaultControl(document.forms[0].UserID);</script>';
}
include('includes/footer.inc');
?>
